!function () {
    layui.config({base: '/layui/lay/modules/'}).use(['table', 'laydate', 'dateformat', 'form'], function () {
        //定义
        var $ = layui.jquery,
            table = layui.table,
            dateformat = layui.dateformat,
            form = layui.form,
            laydate = layui.laydate;


        //初始化渲染列表
        table.render({
            elem:"#dictTable"
            ,url:"/dict/listPage"
            ,method: 'post'
            ,cellMinWidth:80
            ,request: {pageName: 'pageNum', limitName: 'pageSize'}
            ,page: true
            ,cols:[[
                /*{type: 'checkbox', fixed: 'left'},*/
                {field: 'id', title: 'ID', width: 80},
                {field: 'code', title: '字典类型', width: 160},
                {field: 'name', title: '字典名称', width: 160},
                {field: 'tips' ,title :'提示',width:120},
                {fixed: 'right', title: '操作', toolbar: '#barDemo', width: 180, align: 'center'}
            ]],

        });

        //新增
        $('#addNew').click(function () {
            form.val('dictForm', {
                id:'',
                code: '',
                name: '',
                tips:''
            });
            //初始化
            var dictFrom = $("#dictForm");
            dictFrom.find("div[name=itemHtml]").remove();
            form.render('radio');
            layer.open({
                type: 1, maxmin: true, title: '添加字典', area: ['1052px', '550px'],
                content: $('#dictForm').show(), btn: ['保存', '取消'], yes: function () {
                    //保存用户
                    $('#saveDict').click();
                }, btn2: function () {
                    layer.closeAll();
                }, end: function () {
                    $('#dictForm').hide();
                }
            });
        });

        //监听工具条
        table.on('tool(dictFilter)',function(obj){
            var data = obj.data;
            if( obj.event ==='detail'){
                viewDict(data.id);
                return false;
            } else if( obj.event ==='del'){
                layer.confirm('真的删除字典项吗', function (index) {
                    delDict(data.id);
                    return false;
                });
            } else if( obj.event ==='edit'){
                editDict(data.id);
                return false;
            }
        });

        //重新加载列表
        function reloadData(){
            table.reload('dictTable', {where: { dictName: $('#queryName').val()}});
        }

        // 重置点击事件
        $('#resetSearch').click(function () {
            $('#queryTools input').val('');
            $('#queryTools select').val('');

            table.reload('dictTable', {where: { dictName: $('#queryName').val()},page: {curr: 1}});
        });

        //删除用户
        function delDict( id ){
            $.ajax({
                async: false,
                type: 'post',
                url: '/dict/delDict?id=' + id,
                success: function (result) {
                    if (result && result.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        reloadData();
                    }
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        };

        //查询字典信息
        function viewDict( id ){
            $.ajax({
                async: false,
                url: '/dict/findDictById?id=' + id,
                success: function (result) {
                    if (result && result.code == 200) {
                        var data = result.data;
                        form.val('dictView', {
                            id: data.id,
                            code: data.code,
                            name: data.name,
                            tips: data.tips
                        });
                        //初始化子类目
                        if( data.itemList ){
                            var dictFrom = $("#dictView");
                            dictFrom.find("div[name=itemHtml]").remove();
                            for(var item in data.itemList ){
                                var addItem = $("div[name=itemHtml]:first").clone();//构建页面
                                addItem.find('input[name=codeItem]').val(data.itemList[item].codeItem);//赋值
                                addItem.find('input[name=nameItem]').val(data.itemList[item].nameItem);//赋值
                                addItem.find('input[name=numItem]').val(data.itemList[item].numItem);//赋值
                                addItem.show();
                                dictFrom.append(addItem);
                                $(addItem).find("button[name=delItem]").remove();
                            }

                            dictFrom.find('input').attr("disabled",true);
                        }


                        layer.open({
                            type: 1, maxmin: true, title: '查看字典项', area: ['1052px', '550px'],
                            content: $('#dictView').show(), btn2: function () {
                                layer.closeAll();
                            }, end: function () {
                                $('#dictView').hide();
                            }
                        });
                    } else
                        layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        };

        //修改字典项
        function editDict( id ){
            $.ajax({
                async: false,
                url: '/dict/findDictById?id=' + id,
                success: function (result) {
                    if (result && result.code == 200) {
                        var data = result.data;
                        form.val('dictForm', {
                            id: data.id,
                            code: data.code,
                            name: data.name,
                            tips: data.tips
                        });
                        //初始化子类目
                        if( data.itemList ){
                            var dictFrom = $("#dictForm");
                            dictFrom.find("div[name=itemHtml]").remove();
                            for(var item in data.itemList ){
                                var addItem = $("div[name=itemHtml]:first").clone();//构建页面
                                addItem.find('input[name=codeItem]').val(data.itemList[item].codeItem);//赋值
                                addItem.find('input[name=nameItem]').val(data.itemList[item].nameItem);//赋值
                                addItem.find('input[name=numItem]').val(data.itemList[item].numItem);//赋值
                                addItem.show();
                                dictFrom.append(addItem);
                                var delItem = $(addItem).find("button[name=delItem]");
                                $(delItem).on("click",function(){
                                    $(this).parent().remove();
                                });
                            }
                        }

                        layer.open({
                            type: 1, maxmin: true, title: '编辑字典项', area: ['1052px', '550px'],
                            content: $('#dictForm').show(), btn: ['保存', '取消'], yes: function () {
                                $('#saveDict').click();
                            }, btn2: function () {
                                layer.closeAll();
                            }, end: function () {
                                $('#dictForm').hide();
                            }
                        });
                    } else
                        layer.alert(result.msg || '请求失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
        }

        // 搜索表格数据
        $('#renderTable').on('click', function () {
            table.reload('dictTable', {where: { dictName: $('#queryName').val()}});
        });

        //增加字典项
        $(document).on("click",'#addItem',function(data){

            var dictFrom = $("#dictForm");
            var addItem = $("div[name=itemHtml]:first").clone();
            //清理原有值
            $.each(addItem.find('input'),function(){
                $(this).val('');
            })
            addItem.show();
            dictFrom.append(addItem);
            var delItem = $(addItem).find("button[name=delItem]");
            $(delItem).on("click",function(){
                $(this).parent().remove();
            });
            return false;
        });


        //提交字典编辑
        form.on('submit(editDict)',function(data){
            //获取url
            var postUrl = !data.field['id'] ? '/dict/addDict' : '/dict/updateDict';
            //收集数据
            var dataJson={},itemList=[];
            $("#dictForm [name='itemHtml']").each(function(){
                var item = {};
                var codeItem = $(this).find("[name='codeItem']").val();
                var nameItem = $(this).find("[name='nameItem']").val();
                var numItem = $(this).find("[name='numItem']").val();
                item["codeItem"] = codeItem;
                item["nameItem"] = nameItem;
                item["numItem"] = numItem;

                itemList.push(item);
            });
            dataJson["id"] = data.field.id;
            dataJson["code"] = data.field.code;
            dataJson["name"] = data.field.name;
            dataJson["tips"] = data.field.tips;
            dataJson["itemList"] = itemList;
            $.ajax({
                async: false, type: 'post', traditional: true,
                contentType:"application/json;charset=UTF-8",
                data: JSON.stringify(dataJson), url: postUrl,
                success: function (data) {
                    layer.closeAll();
                    if (data && data.code == 200) {
                        layer.alert('操作成功！', {icon: 1, title: '提示'});
                        table.reload('dictTable', {where: {pageNum: 1, condition: $('#queryName').val()}});
                    } else
                        layer.alert(data.msg || '操作失败了！', {icon: 5, title: '提示'});
                },
                error: function () {
                    layer.closeAll();
                    layer.alert('服务器出错啦！', {icon: 2, title: '错误'});
                }
            });
            return false;
        });
    });
}();